package com.yungu.swift.assets.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.cloudauth.model.v20180916.*;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.yungu.swift.assets.driver.model.dto.DriverFaceRecognitionDto;
import org.springframework.stereotype.Component;

import java.util.Date;

import static com.yungu.swift.assets.config.NacosListener.ALIYUN_CONFIG;

/**
 * 人脸识别操作
 */
@Component
public class FaceRecognitionUtils {

    private static String regionId = "cn-hangzhou";


    /**
     * 阿里云RPBioOnly方案 仅活体识别 服务端使用姓名、身份证号
     *
     * @return
     */
    public static DriverFaceRecognitionDto rPBioOnly(String ticketId, String binding) {
        return bioOnly(ticketId, binding, ALIYUN_CONFIG.getFirstCertificationBiz());
    }

    /**
     * 阿里云FVBioOnly方案 仅活体识别 服务端使用留底照片
     *
     * @return
     */
    public static DriverFaceRecognitionDto fVBioOnly(String ticketId, String binding) {
        return bioOnly(ticketId, binding, ALIYUN_CONFIG.getAgainCertificationBiz());
    }

    private static DriverFaceRecognitionDto bioOnly(String ticketId, String binding, String biz) {
        DriverFaceRecognitionDto driverFaceRecognitionEntity = new DriverFaceRecognitionDto();
        //创建DefaultAcsClient实例并初始化
        IAcsClient client = buildIAcsClient();
        //服务端发起认证请求, 获取到token
        GetVerifyTokenRequest getVerifyTokenRequest = new GetVerifyTokenRequest();
        getVerifyTokenRequest.setBiz(biz.replaceAll("\r|\n", ""));
        getVerifyTokenRequest.setTicketId(ticketId);
        getVerifyTokenRequest.setSysMethod(MethodType.POST);
        //通过binding参数传入业务已经采集的认证资料，其中人像留底照片为必要字段
        //请控制单张图片大小在 2M 内，避免拉取超时
        getVerifyTokenRequest.setBinding(binding);
        try {
            GetVerifyTokenResponse response = client.getAcsResponse(getVerifyTokenRequest);
            //token默认30分钟时效，每次发起认证时都必须实时获取
            String token = response.getData().getVerifyToken().getToken();
            //构造返回值
            buildFaceRecognition(driverFaceRecognitionEntity, ticketId, token, ALIYUN_CONFIG.getAccessKeyId(),
                    ALIYUN_CONFIG.getAccessKeySecret(), regionId, biz);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return driverFaceRecognitionEntity;
    }


    /**
     * 获取认证资料
     *
     * @return
     */
    public static DriverFaceRecognitionDto getMaterials(DriverFaceRecognitionDto driverFaceRecognitionEntity) {
        String biz = driverFaceRecognitionEntity.getBiz();
        String ticketId = driverFaceRecognitionEntity.getUuid();
        //创建DefaultAcsClient实例并初始化
        IAcsClient client = buildIAcsClient();
        //-1 未认证, 0 认证中, 1 认证通过, 2 认证不通过
        int statusCode = -1;
        GetStatusRequest getStatusRequest = new GetStatusRequest();
        getStatusRequest.setBiz(biz.replaceAll("\r|\n", ""));
        getStatusRequest.setTicketId(ticketId);
        try {
            GetStatusResponse response = client.getAcsResponse(getStatusRequest);
            statusCode = response.getData().getStatusCode();
            driverFaceRecognitionEntity.setStatus(statusCode);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }

        GetMaterialsRequest getMaterialsRequest = new GetMaterialsRequest();
        getMaterialsRequest.setBiz(biz.replaceAll("\r|\n", ""));
        getMaterialsRequest.setTicketId(ticketId);
        //认证通过or认证不通过
        if (1 == statusCode || 2 == statusCode) {
            driverFaceRecognitionEntity.setCertificationTime(new Date());
            try {
                GetMaterialsResponse response = client.getAcsResponse(getMaterialsRequest);
                //后续业务处理
                GetMaterialsResponse.Data data = response.getData();
                //设置认证照片
                driverFaceRecognitionEntity.setFacePic(data.getFacePic());
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }
        return driverFaceRecognitionEntity;
    }

    /**
     * 构造认证记录
     */
    private static void buildFaceRecognition(DriverFaceRecognitionDto driverFaceRecognitionEntity, String ticketId, String token, String accessKeyId, String accessKeySecret, String regionId, String biz) {
        //同时作为认证的ticketId
        driverFaceRecognitionEntity.setUuid(ticketId);
        driverFaceRecognitionEntity.setToken(token);
        driverFaceRecognitionEntity.setAccessKeyId(accessKeyId);
        driverFaceRecognitionEntity.setAccessKeySecret(accessKeySecret);
        driverFaceRecognitionEntity.setRegionId(regionId);
        driverFaceRecognitionEntity.setBiz(biz);
    }

    /**
     * 构造人脸识别请求客户端
     *
     * @return
     */
    private static IAcsClient buildIAcsClient() {
        //创建DefaultAcsClient实例并初始化
        DefaultProfile profile = DefaultProfile.getProfile(
                //默认
                regionId,
                //您的Access Key ID
                ALIYUN_CONFIG.getAccessKeyId(),
                //您的Access Key Secret
                ALIYUN_CONFIG.getAccessKeySecret());
        return new DefaultAcsClient(profile);
    }

}